const Db = require('./db')
const vk = require('./vk')
const jwt = require('jsonwebtoken')

function checkToken(token){ //检测token
  return new Promise((resolve, reject) => {
    let t = token.split(" ")
    let t1 = t[0]
    let t2 = t[1]
    if(/^Bearer$/i.test(t1)){
      jwt.verify(t2,"adminToken",(err,decoded)=>{
        // console.log("err,decoded ",err,decoded)
        if(err){
          switch(err.name){
            case "TokenExpiredError":
              return resolve([400,"请求失败，登入过期",null])
            break;
          }
        }else{
          resolve([200,"ok",decoded.username]) 
        }
      })
    }else{
      resolve([400,"请求失败，未登入",null]) 
    }
  });
}

class middleware
{
  /**
   *
   * 检测用户权限中间件
   * @static
   * @memberof middleware
   */
  static async check_authority(ctx,next){
    // let user_id = ctx.method=='GET'?ctx.query.user_id:ctx.request.body.user_id
    // 根据path获取权限列表=>有此权限规则，则开始判断，没有则next
    let data = {
      sql: "SELECT * FROM vk_admin_authority_list WHERE url = ? AND is_use = 1",
      values:[ctx.request.path]
    }
    let [err,res] = await Db.query(data)
    if(err){return ctx.body = vk.showData(500,err,"请求错误")}
    if(res.length != 0){
      let adminToken = ctx.headers['authori-zation']
      let [code,msg,username] = await checkToken(adminToken)
      switch(code){
        case 400:
          return ctx.body = vk.showData(400,[],msg)
        break;
      }
      let authorityId = res[0].id
      let data2 = {
        sql:"SELECT r.rules FROM vk_admin a INNER JOIN vk_admin_authority_rule r ON a.username = ? AND a.rule_id = r.id",
        values:[username]
      }
      let [err2,res2] = await Db.query(data2)
      if(err2){return ctx.body = vk.showData(500,err2,"请求错误")}
      if(!res2){return ctx.body = vk.showData(500,[],"用户不存在")}//判断user_id不存在而输出的null
      if(res2[0].rules.length == 0){return ctx.body = vk.showData(500,[],"您没有操作权限")}
      let rules = res2[0].rules.split(",")
      let f = rules.find(e=>e == authorityId)
      if(!f){return ctx.body = vk.showData(500,[],"您没有操作权限")}
      await next()
    }else{
      await next()
    }
  }
}

module.exports = middleware